package com.dhh.sky.activity;

import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.MenuItem.OnMenuItemClickListener;
import com.actionbarsherlock.view.SubMenu;
import com.dhh.sky.R;
import com.dhh.sky.SDAApplication;
import com.dhh.sky.model.SkyDriveAlbum;
import com.dhh.sky.model.SkyDriveObject;
import com.dhh.sky.service.NewOperationService;
import com.dhh.sky.service.OpenOperationService;
import com.dhh.sky.util.CUtil;
import com.dhh.sky.util.Constant;
import com.dhh.sky.widget.FileListActionMode;
import com.dhh.sky.widget.FileListAdapter;
import com.microsoft.live.LiveConnectClient;
import com.microsoft.live.LiveDownloadOperation;
import com.microsoft.live.LiveDownloadOperationListener;
import com.microsoft.live.LiveOperationException;

public class FileListActivity extends BasicActivity implements ActionBar.OnNavigationListener{
	private ActionMode mMode;
	private ListView listView;
	private FileListAdapter adapter;
	private boolean isAMActive = false;
	private LinearLayout loading;
	private FileListActivity context;
	private LinearLayout upButton;
	private MenuItem gridAction;
	private TextView locationView;
	private View locationLine;
	private Stack<String> mPrevFolderNames = new Stack<String>();
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.file_list); 	
		
		Bundle params = this.getIntent().getExtras();
		if(params!=null && params.getString(Constant.PARAM_PATH)!=null){
			currentPath = params.getString(Constant.PARAM_PATH);
		}
		
		context = this;
		initView();
	}	
	
	@Override
	public void onStart(){
		super.onStart();
		initData();
	}
	
	@Override
	public void onResume(){
		super.onResume();
	}
	
	
	@Override
	public boolean dispatchKeyEvent(KeyEvent event){ 
	    if(isAMActive) {
	        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
	        	refreshItems();
	           return true; 
	        }
	    }
	    return super.dispatchKeyEvent(event);
	}
	
	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event){
		if(keyCode == KeyEvent.KEYCODE_BACK){
			if(Constant.SKYFRIVE_PATH_HOME.equalsIgnoreCase(currentPath)){
				this.showDialog(0);
				return true;
			}else if(Constant.SKYFRIVE_PATH_RECENT_DOCS.equalsIgnoreCase(currentPath) || Constant.SKYFRIVE_PATH_SHARED.equalsIgnoreCase(currentPath)){
				return super.onKeyDown(keyCode, event);
			}else{
				SkyDriveObject file = fm.getFile(currentPath);
				if(file!=null){
					currentPath = file.getParentId();
				}else{
					currentPath = Constant.SKYFRIVE_PATH_HOME;
				}		
				mPrevFolderNames.pop();
				this.initData();			
				return true;
			}						
		}
		
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
    protected Dialog onCreateDialog(final int id) {
		Dialog dialog = null;
		 switch (id) {
         	case 0: {
         		AlertDialog.Builder builder = new AlertDialog.Builder(this);
         		builder.setTitle(context.getString(R.string.title_exist));
         		builder.setMessage(context.getString(R.string.msg_exist_confirm));
         		builder.setPositiveButton(context.getString(R.string.label_ok), 
         				new OnClickListener() {
			            	@Override
			            	public void onClick(DialogInterface dialog, int which) {
			            		context.finish();
			            	}
         				});
         		builder.setNegativeButton(context.getString(R.string.label_cancel), 
         				new OnClickListener() {
				             @Override
				             public void onClick(DialogInterface dialog, int which) {
				                dialog.cancel();
				             }
         				});
         		dialog = builder.create();
         	}
         }
		return dialog;
	}
	
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		//TODO when copy / move /delete and so on, show progress status
		if(resultCode==Constant.REQ_OPERATION_COPY || resultCode==Constant.REQ_OPERATION_MOVE){
			onProgressStatus(true);
		}else{
			onProgressStatus(false);
		}
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getSupportActionBar().setTitle("SkyDrive");
        if(Constant.SKYFRIVE_PATH_HOME.equals(currentPath)){
        	getSupportActionBar().setTitle("SkyDrive");
		}else if(Constant.SKYFRIVE_PATH_RECENT_DOCS.equals(currentPath)){
			getSupportActionBar().setTitle("Recent Docs");
		}else if(Constant.SKYFRIVE_PATH_SHARED.equals(currentPath)){
			getSupportActionBar().setTitle("Shared Files");
		}
		refreshAction = menu.add(getString(R.string.ab_refresh));
		refreshAction.setIcon(R.drawable.stat_notify_sync);
		refreshAction.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
		refreshAction.setOnMenuItemClickListener(new OnMenuItemClickListener(){
			@Override
			public boolean onMenuItemClick(MenuItem item) {	
				doSync();
				return true;
			}
		});
        
        MenuItem upload = menu.add(getString(R.string.ab_upload));
        upload.setIcon(R.drawable.ic_ab_upload);
        upload.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        upload.setOnMenuItemClickListener(new OnMenuItemClickListener(){
			@Override
			public boolean onMenuItemClick(MenuItem item) {	
				if(!CUtil.isNetworkAvailable(context)){
					context.showToast(context.getString(R.string.msg_error_network_operation), true);
				}else{
					Intent intent = new Intent(FileListActivity.this,FilePickActivity.class);
					intent.putExtra(Constant.PARAM_PATH, currentPath);
					startActivityForResult(intent, Constant.REQ_OPERATION_UPLOAD);
				}
				
				return true;	
			}
		});
        
        gridAction = menu.add(getString(R.string.ab_grid));
        gridAction.setVisible(false);
        gridAction.setIcon(R.drawable.ic_collections_view_as_grid);
        gridAction.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        gridAction.setOnMenuItemClickListener(new OnMenuItemClickListener(){
			@Override
			public boolean onMenuItemClick(MenuItem item) {					
				if(!CUtil.isNetworkAvailable(context)){
					context.showToast(context.getString(R.string.msg_error_network_operation), true);
				}else{
					Intent intent = new Intent(FileListActivity.this,ImageGridActivity.class);
					intent.putExtra(Constant.PARAM_PATH, currentPath);
					startActivity(intent);
				}
				return true;
			}});
        
        SubMenu create = menu.addSubMenu(getString(R.string.ab_new));
        create.setIcon(R.drawable.ic_add);
        
        MenuItem addFolder = create.add(R.string.ab_folder_new);       
        addFolder.setOnMenuItemClickListener(new OnMenuItemClickListener(){
			@Override
			public boolean onMenuItemClick(MenuItem item) {	
				if(!CUtil.isNetworkAvailable(context)){
					context.showToast(context.getString(R.string.msg_error_network_operation), true);
				}else{
					final Dialog dialog = new Dialog(FileListActivity.this);
					dialog.setContentView(R.layout.dialog_new_folder);
					dialog.setTitle(FileListActivity.this.getString(R.string.title_new_folder));
					dialog.findViewById(R.id.fn_cancel).setOnClickListener(new View.OnClickListener(){
						@Override
						public void onClick(View v) {
							//FileListActivity.this.refreshItems();
							dialog.dismiss();						
						}});
					dialog.findViewById(R.id.fn_add).setOnClickListener(new View.OnClickListener(){
						@Override
						public void onClick(View v) {
							try {
								EditText nameEdit = (EditText) dialog.findViewById(R.id.fn_name);
								EditText descEdit = (EditText) dialog.findViewById(R.id.fn_description);
								String title = nameEdit.getText().toString();
								String desc = descEdit.getText().toString();
								
								if(title==null || title.trim().length()==0){
									showToast("Folder name cannot be empty!",true);
								}else{
									JSONObject file = new JSONObject();
									file.put("name", title);
									file.put("description", desc);
									String meta = file.toString();
									om.addNewFolderOperation(currentPath, meta);
									//FileListActivity.this.refreshItems();
									onProgressStatus(true);
									Intent intent = new Intent(FileListActivity.this,NewOperationService.class);
									FileListActivity.this.startService(intent);
									dialog.dismiss();
								}								
							} catch (Exception e) {
								Log.e(Constant.TAG, e.getMessage(), e);
								dialog.dismiss();
							}
						}});
					dialog.show();
				}			
				
				return true;
			}});
        
        MenuItem addText = create.add(R.string.ab_create_text);   
        addText.setOnMenuItemClickListener(new OnMenuItemClickListener(){
			@Override
			public boolean onMenuItemClick(MenuItem item) {
				Intent intent = new Intent(context,EditorActivity.class);
    			intent.putExtra(Constant.PARAM_OPERATION, EditorActivity.TEXT_FILE_CREATE);
    			intent.putExtra(Constant.PARAM_PATH, currentPath);
    			context.startActivity(intent);
				return true;
			}
        });
        
        if(currentPath.equals(Constant.SKYFRIVE_PATH_RECENT_DOCS) || currentPath.equals(Constant.SKYFRIVE_PATH_SHARED)){
        	upload.setVisible(false);
        	gridAction.setVisible(false);
        	create.getItem().setVisible(false);
        }
        
        return true;
    }

	public void initView(){
		initActionBar();
		//initListNavigation();
		loading = (LinearLayout) this.findViewById(R.id.td_loading);
		listView = (ListView) this.findViewById(R.id.file_list);
		adapter = new FileListAdapter(this,currentPath);
		listView.setTextFilterEnabled(true);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
				if(!isAMActive){
					SkyDriveObject file = adapter.getItem(position);
					if(file.isFolder()){
						context.refreshItems();
						currentPath = adapter.getItem(position).getId();
						adapter.setPath(currentPath);
						mPrevFolderNames.push(file.getName());
						initData();
					}else{
						fm.openFile(context, file);
					}
				}else{
					adapter.selectFile(view, position);
				}
			}
		});
		
		upButton = (LinearLayout) this.findViewById(R.id.button_up);
		upButton.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View v) {
				SkyDriveObject file = fm.getFile(currentPath);
				if(file!=null){
					currentPath = file.getParentId();
					mPrevFolderNames.pop();
				}else{
					currentPath = Constant.SKYFRIVE_PATH_HOME;
					mPrevFolderNames.clear();
				}		
				initData();
				if(isAMActive){
					isAMActive = false;
					adapter.unSelectFiles();
					modeChanged();
				}
			}
		});
		
		locationView = (TextView) this.findViewById(R.id.fl_location);
		locationLine = this.findViewById(R.id.fl_location_seperator);
	}
	
	private void initUpButton(){
		if(Constant.SKYFRIVE_PATH_HOME.equals(currentPath) || Constant.SKYFRIVE_PATH_RECENT_DOCS.equals(currentPath) || Constant.SKYFRIVE_PATH_SHARED.equals(currentPath)){
			upButton.setVisibility(View.GONE);
		}else{
			upButton.setVisibility(View.VISIBLE);
		}
	}
	
	private void initLoaction(){
		if(mPrevFolderNames.size()==0){
			locationView.setVisibility(View.GONE);
			locationLine.setVisibility(View.GONE);
		}else{
			Iterator<String> ite = mPrevFolderNames.iterator();
			StringBuffer location = new StringBuffer();
			location.append("SkyDrive:/");
			while(ite.hasNext()){
				location.append("/");
				location.append(ite.next().toString());
			}

			locationView.setVisibility(View.VISIBLE);
			locationLine.setVisibility(View.VISIBLE);
			locationView.setText(location.toString());
		}
	}
	
	private void refreshActionBar(){
		if(Constant.SKYFRIVE_PATH_HOME.equals(currentPath)){
	        getSupportActionBar().setTitle("SkyDrive");
	        if(gridAction!=null)	
	        	gridAction.setVisible(false);
		}else if(Constant.SKYFRIVE_PATH_RECENT_DOCS.equals(currentPath)){
			getSupportActionBar().setTitle("Recent Docs");
			if(gridAction!=null)	
	        	gridAction.setVisible(false);
		}else if(Constant.SKYFRIVE_PATH_SHARED.equals(currentPath)){
			//TODO replace from resource file.
			getSupportActionBar().setTitle("Shared Files");
			if(gridAction!=null)	
	        	gridAction.setVisible(false);
		}else{
			SkyDriveObject file = fm.getFile(currentPath);
	        getSupportActionBar().setTitle(file.getName());
	        if(SkyDriveAlbum.TYPE.equalsIgnoreCase(file.getType())){
	        	gridAction.setVisible(true);
	        }else{
	        	gridAction.setVisible(false);
	        }
		}
	}	

	public void initData(){		
		adapter.setPath(currentPath);
		adapter.loadFiles();
		adapter.notifyDataSetChanged();	

		initUpButton();
		initLoaction();
		refreshActionBar();
		
		if(fm.needSync(currentPath)){
			doSync();
		}	
	}
	
	public void doSync(){
		if(adapter.getCount()>0){
			onProgressStatus(true);
		}else if(fm.getFolderChildrenCount(currentPath)>0){
			onProgressStatus(true);
			listView.setVisibility(View.GONE);
			loading.setVisibility(View.VISIBLE);
		}
		
		refreshAsync();		
	}
	
	public void loadRecentDoc(){
		listView.setVisibility(View.GONE);
		loading.setVisibility(View.VISIBLE);
	}

	public void modeChanged(){
		Long mode = adapter.getMode();
		
		if(mode.longValue() == FileListActionMode.MODE_NONE){
			if (mMode != null) {
                mMode.finish();
                mMode = null;
                isAMActive = false;
            }
		}else{
			if(mMode==null){
				mMode = this.startActionMode(new FileListActionMode(this));
			}
			
			mMode.getMenu().getItem(0).setVisible(true);
			mMode.getMenu().getItem(1).setVisible(true);
			mMode.getMenu().getItem(2).setVisible(true);
			mMode.getMenu().getItem(3).setVisible(true);
			mMode.getMenu().getItem(4).setVisible(true);
			mMode.getMenu().getItem(5).setVisible(true);
			
			if(mode.longValue() == FileListActionMode.MODE_ALL){
				mMode.getMenu().getItem(0).setVisible(false);	//downlaod menu
				mMode.getMenu().getItem(5).setVisible(false);	//share menu
			}
			
			if(adapter.isSingleChecked()){
				mMode.getMenu().getItem(4).setVisible(true);	//rename menu
			}else{
				mMode.getMenu().getItem(4).setVisible(false);	//rename menu
				mMode.getMenu().getItem(5).setVisible(false);	//share menu
			}
			
			if(currentPath.equals(Constant.SKYFRIVE_PATH_RECENT_DOCS) || currentPath.equals(Constant.SKYFRIVE_PATH_SHARED)){
				mMode.getMenu().getItem(1).setVisible(false);
				mMode.getMenu().getItem(2).setVisible(false);
				mMode.getMenu().getItem(3).setVisible(false);
				mMode.getMenu().getItem(4).setVisible(false);
				mMode.getMenu().getItem(5).setVisible(false);
			}
			
			isAMActive = true;
		}
	}
	
	public void refresh(){	
		isAMActive = false;
		if(mMode!=null){
			mMode.finish();		
			mMode = null;
		}
		
		initData();
	}
	
	public void refreshItems(){
		if(adapter!=null){
			adapter.unSelectFiles();
			adapter.notifyDataSetChanged();
		}
		if(mMode!=null){
			this.modeChanged();
			mMode = null;
		}
		isAMActive = false;
	}	
	
	public void releaseMode(){
		if(adapter!=null){
			adapter.unSelectFiles();
		}
		
		mMode = null;
		isAMActive = false;
	}
	
	public String[] getItemsNameSelected(){
		List<SkyDriveObject> items = adapter.getItemsSelected();
		if(items.size()==0){
			return new String[]{};
		}else{
			String[] pathes = new String[items.size()];
			for(int i=0; i<items.size(); i++){
				pathes[i] = items.get(i).getId();
			}

			return pathes;
		}
	}
	
	public List<SkyDriveObject> getItemSeleted(){
		return adapter.getItemsSelected();
	}
	
	public void hideSelectedItem(){
		adapter.hideItemsSelected();
	}
	
	public void shareFile(String path){
		new ShareTask().execute(new String[]{path});
	}
	
	public class FileSyncTask extends AsyncTask<Void, Void, Boolean>{
		boolean isInitCon = false;
		
		@Override
		protected Boolean doInBackground(Void... params) {
			if (!CUtil.isNetworkAvailable(context)) {				
				sendToast(getString(R.string.msg_error_network));
				return false;
			}else{
				if(((SDAApplication)context.getApplication()).getConnectClient()==null){
					isInitCon = true;
				}
				fm.doSync(FileListActivity.this, currentPath);
				return true;
			}			
		}
		
		@Override
        protected void onPostExecute(final Boolean isLogin) {
			if(!isInitCon){
				refreshHandler.sendEmptyMessage(0);
			}
		}		
	}	
	
	public class LoadRecentDocTask extends AsyncTask<Void, Void, Boolean>{
		boolean isInitCon = false;
		
		@Override
		protected Boolean doInBackground(Void... params) {
			if (!CUtil.isNetworkAvailable(context)) {				
				sendToast(getString(R.string.msg_error_network));
				return false;
			}else{
				if(((SDAApplication)context.getApplication()).getConnectClient()==null){
					isInitCon = true;
				}
				fm.doSync(FileListActivity.this, currentPath);
				return true;
			}			
		}
		
		@Override
        protected void onPostExecute(final Boolean isLogin) {
			if(!isInitCon){
				refreshHandler.sendEmptyMessage(0);
			}
		}		
	}	
	
	class ShareTask  extends AsyncTask<String, Void, Boolean> {
    	private final ProgressDialog progress = new ProgressDialog(context);
    	private String id;
    	private String name;
    	
    	protected void onPreExecute() {
    		//TODO replace from resource
            progress.setMessage("Downloading the file...");
            progress.show();
        }

		@Override
		protected Boolean doInBackground(String... args) {
			Boolean flag = false;
			this.id = args[0];			
			name = fm.getFile(id).getName();
			
			try{
				String dir = Environment.getExternalStorageDirectory().getPath();
				File director = new File(dir+"/SkyDrive");
				if(!director.exists()) director.mkdir();										
				File file = new File(dir+"/SkyDrive/"+name);
				if(file.exists()){
					progress.dismiss();
					Message msg = CUtil.buildMessage();
					msg.getData().putBoolean(Constant.PARAM_DONE, true);
					msg.getData().putString(Constant.PARAM_PATH, name);
					shareHandler.sendMessage(msg);
					return true;
				}else{
					if(CUtil.isNetworkAvailable(context)){ 
						LiveConnectClient client = ((SDAApplication) getApplication()).getConnectClient();
						if(client!=null){
							
							if(file.exists()){
								file.delete();
								file.createNewFile();
							}
							client.downloadAsync(id, file, new LiveDownloadOperationListener(){
								@Override
								public void onDownloadCompleted(LiveDownloadOperation operation) {	
									progress.dismiss();
									Message msg = CUtil.buildMessage();
									msg.getData().putBoolean(Constant.PARAM_DONE, true);
									msg.getData().putString(Constant.PARAM_PATH, name);
									shareHandler.sendMessage(msg);
								}

								@Override
								public void onDownloadFailed(LiveOperationException exception,LiveDownloadOperation operation) {
									progress.dismiss();
									Message msg = CUtil.buildMessage();
									msg.getData().putBoolean(Constant.PARAM_DONE, false);
									shareHandler.sendMessage(msg);
								}

								@Override
								public void onDownloadProgress(int totalBytes,int bytesRemaining,LiveDownloadOperation operation) {
									
								}
							});
						}
					}
				}				
			}catch(Exception e){
				Log.e(Constant.TAG, e.getMessage(),e);
			}
            
			return flag;
		}
		
		@Override
	    protected void onPostExecute(final Boolean success) {
		}
    	
    }
	
	public void refreshAsync(){
		onProgressStatus(true);
		new FileSyncTask().execute();
	}
	
	private Handler refreshHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {    
    		listView.setVisibility(View.VISIBLE);
    		loading.setVisibility(View.GONE);
    		onProgressStatus(false);
    		
    		adapter.setPath(currentPath);
    		adapter.loadFiles();
    		adapter.notifyDataSetChanged();
        }
    };    
    
    private Handler shareHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {   
        	Boolean succes = msg.getData().getBoolean(Constant.PARAM_DONE);
        	if(succes){
            	String name = msg.getData().getString(Constant.PARAM_PATH);
    			Intent sendIntent = new Intent();
    			sendIntent.setAction(Intent.ACTION_SEND);
    			sendIntent.setType("*/*");
    			sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(Environment.getExternalStorageDirectory().getPath()+"/SkyDrive/"+name)));
    			startActivity(sendIntent);
        	}else{
        		//TODO replace from resource
        		showToast("Failed to share the file!",true);
        	}
        }
    }; 
    
    public void showDialogOpen(final String id,final String parent,final String json){
    	if(CUtil.isNetworkAvailable(context)){
    		new AlertDialog.Builder(this)
			.setTitle(getString(R.string.title_dialog_open))
			.setMessage(getString(R.string.msg_download_open))
			.setPositiveButton(getString(R.string.label_ok), new DialogInterface.OnClickListener(){
				@Override
				public void onClick(DialogInterface dialog, int which) {
					om.addOpenOperation(id, parent, json);
					Intent intent = new Intent(context,OpenOperationService.class);
					context.startService(intent);
					updateItemProgress(true,id,parent,3);
				}
			}).setNegativeButton(getString(R.string.label_cancel), null).show();
    	}else{
    		new AlertDialog.Builder(this)
			.setTitle(getString(R.string.title_dialog_alert))
			.setMessage(getString(R.string.msg_error_network_open_file))
			.setPositiveButton(getString(R.string.label_ok), new DialogInterface.OnClickListener(){
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			}).show();
    	}
    	
    	
		
	}

	@Override
	protected void updateItemProgress(boolean isSucc, String id, String path,int progress) {		
		try{
    		if(!currentPath.equalsIgnoreCase(path)){
    			return;
    		}    		
    		
        	int position = -1;  
        	for(int i=0; i<adapter.getCount(); i++){
        		SkyDriveObject obj = adapter.getItem(i);
        		if(obj.getId().equalsIgnoreCase(id)){
        			position = i;
        			break;
        		}
        	}   
        	
        	if(position>=0){
        		int firstPosition = listView.getFirstVisiblePosition() - listView.getHeaderViewsCount();
        		int wantedChild = position - firstPosition;
        		if (wantedChild < 0 || wantedChild >= listView.getChildCount()){
        			return;
        		}
        		        		
        		View itemView = listView.getChildAt(wantedChild);  
        		LinearLayout progressList = (LinearLayout) itemView.findViewById(R.id.progress_list);
        		TextView status = (TextView) itemView.findViewById(R.id.fli_status);
        		View progressValue = progressList.findViewById(R.id.progress_value);
        		
        		if(progress >= 100){
        			progressList.setVisibility(View.INVISIBLE);
        			itemView.findViewById(R.id.fli_downloaded).setVisibility(View.VISIBLE);
        			fm.openFile(context, fm.getFile(id));
        			return;
        		}
        		
        		if(isSucc){
        			progressList.setVisibility(View.VISIBLE);
        			status.setVisibility(View.VISIBLE);
        			LinearLayout.LayoutParams params = new LayoutParams(0, LayoutParams.MATCH_PARENT, progress);
        			progressValue.setLayoutParams(params);       	
        		}else{
        			progressList.setVisibility(View.GONE);
        			status.setVisibility(View.GONE);
        			//TODO replace from resource
        			showToast("Failed to open file!",true);
        		}        		       		        		
        	}
    	}catch(Exception e){
			Log.e(Constant.TAG, e.getMessage(),e);
    	}	
	}  
}